import sqlite3
import os
import shutil
import logging
from PyQt5 import QtCore, QtGui, QtWidgets
from ui_mainwindow import Ui_MainWindow
from PyQt5.QtWidgets import QFileDialog, QMessageBox


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        self.toolButton_source.clicked.connect(self.tb_source_clicked)
        self.toolButton_target.clicked.connect(self.tb_target_clicked)
        self.pushButton_backup.clicked.connect(self.pb_backup_clicked)
        self.pushButton_exit.clicked.connect(self.pb_exit_clicked)

    def tb_source_clicked(self):
        directory = QFileDialog.getExistingDirectory()
        # print('Source:', directory)
        self.lineEdit_source.setText(directory)

    def tb_target_clicked(self):
        directory = QFileDialog.getExistingDirectory()
        # print('Target:', directory)
        self.lineEdit_target.setText(directory)

    def pb_backup_clicked(self):
        # 设置日志
        log_format = '%(asctime)s - %(levelname)s - %(message)s'
        log_datefmt = '%Y/%m/%d %H:%M:%S'
        # logging.basicConfig(filename='DuoKanBackup.log', level=logging.INFO, format=log_format, datefmt=log_datefmt)
        logging.basicConfig(level=logging.INFO, format=log_format, datefmt=log_datefmt)
        log_filehandler = logging.FileHandler(filename='DuoKanBackup.log', encoding='utf-8')
        log_formatter = logging.Formatter(fmt=log_format, datefmt=log_datefmt)
        log_filehandler.setFormatter(log_formatter)
        logging.root.addHandler(log_filehandler)
        # 读取源路径
        source_directory = self.lineEdit_source.text()
        if len(source_directory) == 0:
            QMessageBox.warning(self, '警告', '“要备份的图书和数据库目录”不能为空！', QMessageBox.Ok)
            return
        # 读取目标路径
        target_directory = self.lineEdit_target.text()
        if len(target_directory) == 0:
            QMessageBox.warning(self, '警告', '“备份图书保存到”不能为空！', QMessageBox.Ok)
            return
        target_directory = target_directory.replace('/', '\\')
        # 连接数据库
        database = source_directory + r'\Bookshelf.db'
        connection = sqlite3.connect(database)
        cursor = connection.cursor()
        sql = "select book_uri,book_name,author,file_size,book_revision from books where file_size > 0 and book_state = 'NORMAL'"
        cursor.execute(sql)
        result = cursor.fetchall()
        for book in result:
            # print('Book =', book)
            logging.info(book)
            book_uri = book[0]
            book_name = book[1]
            author = book[2]
            file_size = book[3]
            book_revision = book[4]
            # 检查图书文件名中的非法字符
            book_name = check_book_name(book_name)
            # 修改源图书文件路径
            book_source = str.replace(book_uri, 'file:///storage/emulated/0/DuoKan', source_directory)
            book_source = book_source.replace('/', '\\')
            book_target = target_directory
            # 检查目标路径是否存在
            if not os.path.exists(book_target):
                os.makedirs(book_target)
            book_filename = book_name + ' - ' + author + '.' + book_revision + '.epub'
            book_target = book_target + '\\' + book_filename
            # 检查是否下载过源文件
            if os.path.exists(book_source):
                # 检查图书是否已经完全下载
                if os.path.getsize(book_source) == file_size:
                    # 检查图书是否已经备份过
                    if not os.path.exists(book_target):
                        # print('Copy ', book_source, '...')
                        # print('  To ', book_target, '...')
                        message = '正在备份图书 ' + book_filename
                        self.statusbar.showMessage(message)
                        shutil.copyfile(book_source, book_target)
                        msg = '将图书从 ' + book_source + ' 拷贝到 ' + book_target
                        logging.info(msg)
                    else:
                        message = '图书“' + book_filename + '”已经存在！'
                        self.statusbar.showMessage(message)
                        msg = '图书“' + book_target + '”已经存在！'
                        logging.info(msg)
                else:
                    message = '图书“' + book_filename + '”内容不完整！'
                    self.statusbar.showMessage(message)
                    msg = '图书“' + book_source + '”内容不完整！'
                    logging.info(msg)
            else:
                message = '图书“' + book_filename + '”不存在！'
                self.statusbar.showMessage(message)
                msg = '图书“' + book_source + '”不存在！'
                logging.info(msg)
        cursor.close()
        connection.close()
        self.statusbar.showMessage('图书备份完成!')

    def pb_exit_clicked(self):
        self.close()

def check_book_name(book_name):
    # 检查图书文件名中的非法字符 \ / : * ? " < > | 并替换为中文全角字符
    book_name = str.replace(book_name, '\\', '＼')
    book_name = str.replace(book_name, '/', '／')
    book_name = str.replace(book_name, ':', '：')
    book_name = str.replace(book_name, '*', '×')
    book_name = str.replace(book_name, '?', '？')
    book_name = str.replace(book_name, '"', '〃')
    book_name = str.replace(book_name, '<', '＜')
    book_name = str.replace(book_name, '>', '＞')
    book_name = str.replace(book_name, '|', '｜')
    return book_name
